﻿using System;
using System.Data;
using System.Text;
using System.Reflection;
using System.Collections.Generic;
using System.Data.SqlClient;
using ByteSite.DBUtility;
using ByteSite.Common;
using SqlSugar;
using System.Dynamic;
using System.Linq.Expressions;
using System.Linq;

namespace ByteSite.DAL
{
	/// <summary>
	/// 数据访问类:文章内容
	/// </summary>
	public partial class form
    {
        public SqlSugarClient db;
        private string databaseprefix; //数据库表名前缀
        public form(string _databaseprefix)
        {
            databaseprefix = _databaseprefix;
            db = new DBUtility.DbContext().Db;
        }
        /// <summary>
        /// 是否存在该记录
        /// </summary>
        public bool Exists(string formName, int id)
        {
            object obj = db.Queryable<Entitys.form>().AS(databaseprefix + DTKeys.TABLE_FORM_DATA + formName).Where(x => x.id == id).First();
            if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        public bool Exists(int formId, int id)
        {
            string formName = db.Queryable<Entitys.dt_forms>().Where(x => x.id == formId).First().name;
            object obj = db.Queryable<Entitys.form>().AS(databaseprefix + DTKeys.TABLE_FORM_DATA + formName).Where(x => x.id == id).First();
            if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        /// <summary>
        /// 增加一条数据
        /// </summary>
        public int Add(Entitys.form model)
        {
            //查询频道名称
            string formName = db.Queryable<Entitys.dt_forms>().Where(x => x.id == model.form_id).First().name;
            if (formName.Length == 0)
            {
                return 0;
            }
            try
            {
                db.BeginTran();

                #region 修改主表数据====================
                string table = databaseprefix + DTKeys.TABLE_FORM_DATA + formName;
                model.id = db.Insertable(model).AS(table).ExecuteReturnIdentity();

                //扩展字段信息
                if (model.fields != null)
                {
                    if (model.fields.Count > 0)
                    {
                        model.fields.Add("id", model.id);
                        db.Updateable(model.fields).AS(table).WhereColumns("id").ExecuteCommand();
                    }
                }
                #endregion

                db.CommitTran();
            }
            catch (Exception ex)
            {
                db.RollbackTran();
                return 0;
            }
            return model.id;
        }

		/// <summary>
		/// 更新一条数据
		/// </summary>
		public bool Update(Entitys.form model)
		{
            //查询频道名称Entitys.dt_forms
            string formName = db.Queryable<Entitys.dt_forms>().Where(x => x.id == model.form_id).First().name;
            if (formName.Length == 0)
            {
                return false;
            }

            try
            {
                db.BeginTran();

                #region 修改主表数据====================
                string table = databaseprefix + DTKeys.TABLE_FORM_DATA + formName;
                db.Updateable(model).AS(table).ExecuteCommand();

                //扩展字段信息
                if (model.fields != null)
                {
                    if (model.fields.Count > 0)
                    {
                        model.fields.Add("id", model.id);
                        db.Updateable(model.fields).AS(table).WhereColumns("id").ExecuteCommand();
                    }
                }
                #endregion

                db.CommitTran();
            }
            catch (Exception ex)
            {
                db.RollbackTran();
                return false;
            }
            return true;
		}

		/// <summary>
		/// 删除一条数据
		/// </summary>
		public bool Delete(string formName, int id)
        {
            try
            {
                db.BeginTran();

                string table = databaseprefix + DTKeys.TABLE_FORM_DATA + formName;

                db.Deleteable<Entitys.form>().AS(table).Where(x => x.id == id).ExecuteCommand();

                db.CommitTran();
            }
            catch (Exception ex)
            {
                db.RollbackTran();
                return false;
            }
            return true;
		}

		/// <summary>
		/// 得到一个对象实体
		/// </summary>
        public Entitys.form GetModel(string formName, int id)
        {
            int formId = db.Queryable<Entitys.dt_forms>().Where(x => x.name == formName).First().id;

            string table = databaseprefix + DTKeys.TABLE_FORM_DATA + formName;

            List<Entitys.dt_form_attribute_field> fields = db.Queryable<Entitys.dt_form_attribute_field, Entitys.dt_form_field>((a, s) => new JoinQueryInfos(
                 JoinType.Inner, a.id == s.field_id
             )).Where((a, s) => s.form_id == formId).OrderBy((a, s) => a.is_sys, OrderByType.Desc).OrderBy((a, s) => a.sort_id, OrderByType.Asc).OrderBy((a, s) => a.id, OrderByType.Desc).ToList();

            dynamic dynamicModel = db.Queryable<dynamic>().AS(table).Where(db.DbMaintenance.GetPrimaries(table)[0] + "=@id", new { id = id }).First();
            
            Entitys.form model = new Entitys.form();
            model.fields = new Dictionary<string, object>();

            PropertyInfo[] properties = model.GetType().GetProperties();
            foreach (KeyValuePair<string, object> kvp in dynamicModel)
            {
                if (properties.Any(x => x.Name == kvp.Key))
                {
                    PropertyInfo p = model.GetType().GetProperty(kvp.Key);
                    p.SetValue(model, kvp.Value);
                }
                else
                {
                    model.fields[kvp.Key] = kvp.Value;
                }
            }
            return model;

        }

		/// <summary>
		/// 获得前几行数据
		/// </summary>
        public List<Entitys.form> GetList(string formName, int top, Expression<Func<Entitys.form, bool>> whereExpression, string filedOrder)
        {
            string table = databaseprefix + DTKeys.TABLE_FORM_DATA + formName;
            List<Entitys.form> newList = new List<Entitys.form>();
            List<Entitys.form> list = db.Queryable<Entitys.form>().AS(table).Take(top).Where(whereExpression).OrderBy(filedOrder).ToList();
            foreach (Entitys.form model in list)
            {
                newList.Add(GetModel(formName, model.id));
            }
            return newList;
        }

        /// <summary>
        /// 获得查询分页数据
        /// </summary>
        public List<Entitys.form> GetList(string formName, int pageSize, int pageIndex, Expression<Func<Entitys.form, bool>> whereExpression, List<IConditionalModel> conModels, string sql, string filedOrder, out int recordCount)
        {
            string table = databaseprefix + DTKeys.TABLE_FORM_DATA + formName;
            recordCount = 0;
            Expression<Func<Entitys.form, bool>> expression = t => true;
            List<Entitys.form> newList = new List<Entitys.form>();
            List<Entitys.form> list = db.Queryable<Entitys.form>().AS(table).Where(expression).Where(whereExpression).Where(conModels).Where(sql).OrderBy(filedOrder).ToPageList(pageIndex, pageSize, ref recordCount);
            foreach (Entitys.form model in list)
            {
                newList.Add(GetModel(formName, model.id));
            }
            return newList;
        }

        #region 扩展方法================================
        /// <summary>
        /// 是否存在标题
        /// </summary>
        public bool ExistsTitle(string formName, string title)
        {
            string table = databaseprefix + DTKeys.TABLE_FORM_DATA + formName;
            return db.Queryable<Entitys.form>().AS(table).Where(x => x.data_name == title).Any();
        }

        /// <summary>
        /// 是否存在标题
        /// </summary>
        public bool ExistsTitle(string formName, int formId, string title)
        {
            string table = databaseprefix + DTKeys.TABLE_FORM_DATA + formName;
            return db.Queryable<Entitys.form>().AS(table).Where(x => x.data_name == title && x.form_id == formId).Any();
        }

        /// <summary>
        /// 返回信息标题
        /// </summary>
        public string GetTitle(string formName, int id)
        {
            string table = databaseprefix + DTKeys.TABLE_FORM_DATA + formName;
            Entitys.form model = db.Queryable<Entitys.form>().AS(table).Where(x => x.id == id).First();
            if (model == null)
                return "";
            else
                return model.data_name;
        }

        /// <summary>
        /// 返回数据总数
        /// </summary>
        public int GetCount(string formName, Expression<Func<Entitys.form, bool>> expression)
        {
            string table = databaseprefix + DTKeys.TABLE_FORM_DATA + formName;
            return db.Queryable<Entitys.form>().AS(table).Where(expression).Count();
        }

        /// <summary>
        /// 修改一列数据
        /// </summary>
        public bool UpdateField(string formName, Expression<Func<Entitys.form, Entitys.form>> expression, Expression<Func<Entitys.form, bool>> whereExpression)
        {
            string table = databaseprefix + DTKeys.TABLE_FORM_DATA + formName;
            return db.Updateable<Entitys.form>().AS(table).SetColumns(expression).Where(whereExpression).ExecuteCommand() > 0;
        }
        public bool UpdateField(string formName, Expression<Func<Entitys.form, bool>> expression, Expression<Func<Entitys.form, bool>> whereExpression)
        {
            string table = databaseprefix + DTKeys.TABLE_FORM_DATA + formName;
            return db.Updateable<Entitys.form>().AS(table).SetColumns(expression).Where(whereExpression).ExecuteCommand() > 0;
        }
        #endregion
    }
}

